package com.ruoyi.comm.crud.mapper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.apache.ibatis.binding.MapperProxy;
import org.apache.ibatis.session.SqlSession;

public class MapperUtils {
	
	/***
	 * 从Mapper实例获取Sqlsession对象
	 * @param pvMapper 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static SqlSession getSqlSession(Object pvMapper) {
		if (!Proxy.isProxyClass(pvMapper.getClass()))return null;
		InvocationHandler lvInvHandler=Proxy.getInvocationHandler(pvMapper);
		if (!(lvInvHandler instanceof MapperProxy)) return null;
		MapperProxy lvT = (MapperProxy)lvInvHandler ;
		try {
			Field lvSessField=lvT.getClass().getDeclaredField("sqlSession");
			lvSessField.setAccessible(true);
			try {
				return (SqlSession) lvSessField.get(lvT);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (NoSuchFieldException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
